package com.wuercloud.mq.common;

import org.springframework.amqp.AmqpIllegalStateException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

/**
 * Created by JiangWL on 2017/4/1.
 */
public class MessageConverterUtils {
    private static MessageConverter converter = null;
    /**
     * 此两方法从rabbitTemplate搬出，用于转换消息对象为ampq的Message对象，目的是为做消息上的处理，如针对消息而非队列的过期时间
     * @return
     * @throws IllegalStateException
     */
    private static MessageConverter getRequiredMessageConverter() throws IllegalStateException {
        converter = new SimpleMessageConverter();
        if(converter == null) {
            throw new AmqpIllegalStateException("No \'messageConverter\' specified. Check configuration of RabbitTemplate.");
        } else {
            return converter;
        }
    }
    public static Message convertMessageIfNecessary(Object object) {
        return object instanceof Message?(Message)object:getRequiredMessageConverter().toMessage(object, new MessageProperties());
    }
}
